<template>
  <view class="container">
    <view class="u-page page">
      <view class="u-demo-block">
        <text class="u-demo-block__title">添加收货地址</text>
        <view class="u-demo-block__content form-content">
          <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
          <!-- 表单 -->
          <u--form labelPosition="left" :model="model1" ref="form1">
            
            <u-form-item label="收件人" prop="userInfo.addrUser" borderBottom ref="item1" labelWidth="80">
              <u--input v-model="model1.userInfo.addrUser" border="none" placeholder="请输入收件人"></u--input>
            </u-form-item>
            
            <u-form-item label="联系电话" prop="userInfo.phone" borderBottom ref="item1" labelWidth="80"> 
              <u--input v-model="model1.userInfo.phone" border="none" placeholder="请输入联系电话"></u--input>
            </u-form-item>
            
            <u-form-item label="所在地区" prop="userInfo.region" borderBottom ref="item1" labelWidth="80">
              <u--input v-model="model1.userInfo.region" border="none" placeholder="请选择所在地区"></u--input>
            </u-form-item>
            
            <!-- 简介 -->
            <u-form-item label="详细地址" labelWidth="80" prop="intro" borderBottom ref="item3">
              <u--textarea placeholder="不低于3个字" v-model="model1.intro" count></u--textarea>
            </u-form-item>
            
            <u-form-item label="生日" prop="userInfo.birthday" borderBottom @click="showBirthday = true; hideKeyboard()"
              ref="item1">
              <u--input v-model="model1.userInfo.birthday" disabled disabledColor="#ffffff" placeholder="请选择生日"
                border="none"></u--input>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
          </u--form>
          
          <!-- 底部提交按钮 -->
          <view class="submit-btn">
            <u-button type="success" text="保存收货地址" shape="circle" customStyle="margin-top: 50px" @click="submit"></u-button>
            <u-button type="error" text="重置收货信息" shape="circle" customStyle="margin-top: 10px" @click="reset"></u-button>
          </view>
          
          <!-- 貌似是验证规则? -->
          <u-action-sheet :show="showSex" :actions="actions" title="请选择性别" description="如果选择保密会报错"
            @close="showSex = false" @select="sexSelect">
          </u-action-sheet>
          <u-calendar :show="showCalendar" mode="range" @confirm="calendarConfirm" @close="calendarClose" startText="住店"
            endText="离店" confirmDisabledText="请选择离店日期" :formatter="formatter"></u-calendar>
          <u-code ref="uCode" @change="codeChange" seconds="20" @start="disabled1 = true" @end="disabled1 = false">
          </u-code>
          <u-datetime-picker :show="showBirthday" :value="birthday" mode="date" closeOnClickOverlay
            @confirm="birthdayConfirm" @cancel="birthdayClose" @close="birthdayClose"></u-datetime-picker>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    data() {
      return {
        fileList1: [],
        disabled1: false,
        tips: '',
        value: '',
        showBirthday: false,
        model1: {
          userInfo: {
            addrUser: '',
            phone: '',
            region: '',
            birthday: ''
          },
          intro: '',
          code: ''
        },
        birthday: Number(new Date()),
        actions: [{
            name: '男',
          },
          {
            name: '女',
          },
          {
            name: '保密',
          },
        ],
        rules: {
          'userInfo.name': [{
            type: 'string',
            required: true,
            message: '请填写姓名',
            trigger: ['blur', 'change']
          }, {
            // 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
            validator: (rule, value, callback) => {
              // 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
              return uni.$u.test.chinese(value);
            },
            message: "姓名必须为中文",
            // 触发器可以同时用blur和change，二者之间用英文逗号隔开
            trigger: ["change", "blur"],
          }],
          code: {
            type: 'string',
            required: true,
            len: 4,
            message: '请填写4位验证码',
            trigger: ['blur']
          },
          'userInfo.sex': {
            type: 'string',
            max: 1,
            required: true,
            message: '请选择男或女',
            trigger: ['blur', 'change']
          },
          radiovalue1: {
            type: 'string',
            min: 1,
            max: 2,
            message: '橙子有毒',
            trigger: ['change']
          },
          checkboxValue1: {
            type: 'array',
            min: 2,
            required: true,
            message: '不能太宅，至少选两项',
            trigger: ['change']
          },
          intro: {
            type: 'string',
            min: 3,
            required: true,
            message: '不低于3个字',
            trigger: ['change']
          },
          'userInfo.birthday': {
            type: 'string',
            required: true,
            message: '请选择生日',
            trigger: ['change']
          },
        },
      }
    },
    onReady() {
      // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
      this.$refs.form1.setRules(this.rules)
    },
    computed: {
      ...mapState('user', ['userInfo'])
    },
    methods: {
      ...mapMutations('user', ['changeAddressList']),
      afterRead(event) {
        this.fileList1.push({
          url: event.file,
      		status: 'uploading',
          message: '上传中'
      		})
      },
      navigateBack() {
        uni.navigateBack()
      },
      change(e) {
        // console.log(e);
      },
      calendarConfirm(e) {
      		this.showCalendar = false
        this.model1.hotel = `${e[0]} / ${e[e.length - 1]}`
        this.$refs.form1.validateField('hotel')
      },
      codeChange(text) {
        this.tips = text;
      },
      getCode() {
        if (this.$refs.uCode.canGetCode) {
          // 模拟向后端请求验证码
          uni.showLoading({
            title: '正在获取验证码'
          })
          setTimeout(() => {
            uni.hideLoading();
            // 这里此提示会被this.start()方法中的提示覆盖
            uni.$u.toast('验证码已发送');
            // 通知验证码组件内部开始倒计时
            this.$refs.uCode.start();
          }, 2000);
        } else {
          uni.$u.toast('倒计时结束后再发送');
        }
      },
      
      birthdayClose() {
        this.showBirthday = false
        this.$refs.form1.validateField('userInfo.birthday')
      },
      birthdayConfirm(e) {
        this.showBirthday = false
        this.model1.userInfo.birthday = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
        this.$refs.form1.validateField('userInfo.birthday')
      },
      // 提交
      submit() {
        // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
        this.$refs.form1.validate().then(res => {
      	   uni.$u.toast('校验通过')
      	 }).catch(errors => {
          uni.$u.toast('校验失败')
        })
      },
      // 重置
      reset() {
        const validateList = ['userInfo.addrUser', 'userInfo.phone', 'userInfo.region', 'userInfo.fullAddr', 'userInfo.birthday']
        this.$refs.form1.resetFields()
        this.$refs.form1.clearValidate()
        setTimeout(() => {
          this.$refs.form1.clearValidate(validateList)
          // 或者使用 this.$refs.form1.clearValidate()
        }, 10)
      },
      hideKeyboard() {
      	 uni.hideKeyboard()
      }
    }
  }
</script>

<style lang="scss" scoped>
.container {
  padding-top: 30rpx;
  padding-bottom: 50rpx;
  
  .page {
    width: 90%;
    margin: 0 auto;
    
    .form-content {
      margin-top: 30rpx;
    }
  }
}
</style>
